
let deferredPrompt;

window.addEventListener('beforeinstallprompt', (event) => {
  // Prevent the default browser install prompt
  console.log("beforeinstallprompt");
  event.preventDefault();
  // Stash the event so it can be triggered later
  deferredPrompt = event;

});

const registerServiceWorker = async () => {
    if ("serviceWorker" in navigator) {
        try {
          const registration = await navigator.serviceWorker.register("/sw.js", {
            scope: "/",
          });
          if (registration.installing) {
            console.log("Service worker installing");
          } else if (registration.waiting) {
            console.log("Service worker installed");
          } else if (registration.active) {
            console.log("Service worker active");
          }
        } catch (error) {
          console.error(`Registration failed with ${error}`);
        }
    }
};


registerServiceWorker();

const addResourcesToCache = async (resources) => {
  const cache = await caches.open("v1");
  await cache.addAll(resources);
};

self.addEventListener("install", (event) => {
    const cacheAllowlist = ["v1"];
      event.waitUntil(
        caches.forEach((cache, cacheName) => {
          if (!cacheAllowlist.includes(cacheName)) {
            return caches.delete(cacheName);
          }
        }),
      );
});
self.addEventListener("message", (event) => {
    // event is a MessageEvent object
});

self.addEventListener("fetch", (event) => {
    event.respondWith(caches.match(event.request));
});

self.addEventListener("push", (event) => {
  
});


function gotoRef() {
    console.log("aaaa");
    if(deferredPrompt){
        deferredPrompt.prompt();
        deferredPrompt.userChoice.then((choiceResult) => {
            if (choiceResult.outcome === 'accepted') {
                console.log('User accepted the PWA install prompt');
                } else {
                console.log('User dismissed the PWA install prompt');
                }
                // Reset the deferredPrompt variable
            deferredPrompt = null;
            // Hide the custom install button
        });
    }
}
